<template>
  <!-- 天气查询 -->
  <div class="search">
    <!-- ====================搜索栏 =====================-->
    <div class="input">
      <input
        type="text"
        placeholder="请输入城市名称..."
        v-model.trim="searchData"
      />
    </div>
    <div class="suggest" v-if="searchData" @click="handeleDetail">
      {{ searchData }}
    </div>
    <!-- 列表 -->
    <ListMod></ListMod>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import ListMod from './ListMod.vue';

// 导入请求方法
import { getcityadcode } from '../api/wdata.js';
import { getadcodeweather } from '../api/wdata.js';

//引入pinia
import { useLocalStore } from '@/stores/local';
const { updataWsearch } = useLocalStore();

// 引入路由
import { useRouter } from 'vue-router';
const router = useRouter(); // 获取路由实例

//搜索的城市名
const searchData = ref('');
// 存放搜素城市名 对应adcode
const searchAdcode = ref('');
// 存放 搜索adcode 对应的天气9
const searchWeather0 = ref([]);
const searchWeather9 = ref([]);

// 点击建议框进行跳转 +搜索请求函数
const handeleDetail =
  // 请求数据->城市名 获取 天气
  async () => {
    console.log('搜索结果', searchData.value);
    try {
      // 城市名 获取 adcode
      searchAdcode.value = await getcityadcode(searchData.value);
      console.log('搜索adcode：', searchAdcode.value);
      // adcode获取 天气
      searchWeather0.value = await getadcodeweather(
        searchAdcode.value.geocodes[0].adcode
      );
      searchWeather9.value = searchWeather0.value.forecasts[0].casts;
      console.log('搜索天气', searchWeather9.value);

      // 调用仓库方法，将搜索天气数组保存到 pinia
      updataWsearch(searchWeather9.value);
    } catch (error) {
      console.log('获取失败：', error);
    }
    router.push(`/details/${searchData.value}`);
    searchData.value = '';
  };
</script>

<style lang="scss" scoped>
//================= 搜索框 ====================
.input {
  input {
    width: 100%;
    height: 35px;
    outline: none; /* 输入框触发焦点时，取消显示边框线 */
    font-size: 16px;
    border: none;
    border-bottom: 1px solid #ddd;
    background-color: #00668a;
    /* 使输入框内字体颜色为白色 */
    color: #ffffff;
    padding-left: 20px; /* 提示字靠右 */
  }
  /* 聚焦 - 阴影 */
  input:focus {
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
  }
  /* 提示文字 - 白色 */
  input::placeholder {
    color: #ffffffa4;
  }
}
.suggest {
  padding: 13px 20px;
  color: #ffffff;
  background-color: #004e71;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
}
</style>
